/**
 * @Author: 抱著羊啃 1437670973@qq.com
 * @Date: 2025-05-19
 * @Description: 小说展示功能，负责请求API获取小说数据并渲染到页面
 */

// 在页面加载完成后执行
$(document).ready(function() {
    // 获取小说数据并渲染
    fetchNovels();
});

/**
 * 获取小说数据
 * @param {number} pageNum - 页码，默认为1
 * @param {number} pageSize - 每页数量，默认为27
 * @param {string} novelName - 小说名称，可选
 */
function fetchNovels(pageNum = 1, pageSize = 27, novelName = '') {
    // 构建请求参数
    let params = {
        pageNum: pageNum,
        pageSize: pageSize,
        orderDirection: 'ASC' // 添加正序排序参数
    };
    
    // 如果有小说名称，添加到请求参数
    if (novelName) {
        params.novel_name = novelName;
    }
    
    // 使用jQuery AJAX发起请求
    $.ajax({
        url: '/demo1_war_exploded/API/Novel',
        type: 'GET',
        data: params,
        dataType: 'json',
        success: function(data) {
            if (data.code === 200) {
                // 渲染小说轮播图
                renderNovelsCarousel(data.rows);
                // 移除分页渲染
                // 清空分页容器
                $('#pagination-container').empty();
            } else {
                console.error('获取小说数据失败:', data.msg);
                showError('获取小说数据失败: ' + data.msg);
            }
        },
        error: function(xhr, status, error) {
            console.error('请求出错:', error);
            showError('请求出错: ' + (xhr.responseJSON ? xhr.responseJSON.msg : error));
        }
    });
}

/**
 * 渲染小说轮播图
 * @param {Array} novels - 小说数据数组
 */
function renderNovelsCarousel(novels) {
    // 清空容器
    $('#novels-container').empty();
    
    // 如果没有小说数据
    if (!novels || novels.length === 0) {
        $('#novels-container').html('<div class="col-12 text-center py-5"><h3>暂无小说数据</h3></div>');
        return;
    }
    
    // 创建轮播图容器
    const carouselContainer = $('<div id="novelsCarousel" class="carousel slide" data-bs-ride="carousel" data-bs-interval="5000">');
    $('#novels-container').append(carouselContainer);
    
    // 创建轮播图指示器
    const carouselIndicators = $('<div class="carousel-indicators">');
    
    // 创建轮播图内容
    const carouselInner = $('<div class="carousel-inner">');
    
    // 计算页数（每页9本小说，最多3页）
    const pageCount = Math.min(3, Math.ceil(novels.length / 9));
    
    // 遍历页数
    for (let i = 0; i < pageCount; i++) {
        // 创建指示器
        carouselIndicators.append(`
            <button type="button" data-bs-target="#novelsCarousel" data-bs-slide-to="${i}" ${i === 0 ? 'class="active" aria-current="true"' : ''} aria-label="第${i+1}页"></button>
        `);
        
        // 创建轮播项
        const carouselItem = $('<div>').addClass('carousel-item' + (i === 0 ? ' active' : ''));
        
        // 创建网格容器
        const rowContainer = $('<div>').addClass('row row-cols-1 row-cols-md-3 g-3 py-3');
        
        // 获取当前页的小说（每页9本）
        const pageNovels = novels.slice(i * 9, Math.min((i + 1) * 9, novels.length));
        
        // 遍历当前页的小说
        $.each(pageNovels, function(index, novel) {
            // 全局索引（用于排名）
            const globalIndex = i * 9 + index;
            
            // 排名序号，从1开始
            const rankNum = globalIndex + 1;
            
            // 创建列容器
            const colContainer = $('<div>').addClass('col mb-3');
            
            // 排名序号样式
            let rankClass = '';
            if (rankNum === 1) {
                rankClass = 'rank-first';
            } else if (rankNum === 2) {
                rankClass = 'rank-second';
            } else if (rankNum === 3) {
                rankClass = 'rank-third';
            }
            
            // 构建卡片HTML
            const card = $('<div>').addClass('card novel-card h-100 shadow-sm border-0');
            
            // 卡片内容
            card.html(`
                <div class="card-body p-2">
                    <div class="d-flex align-items-start mb-1">
                        <div class="rank-number ${rankClass} me-2" style="font-size: 18px;">${rankNum < 10 ? '0' + rankNum : rankNum}</div>
                        <div class="d-flex flex-column">
                            <h6 class="novel-title mb-0 text-truncate">${novel.novel_name}</h6>
                            <span class="author-name text-muted small">${novel.username || '未知'}</span>
                        </div>
                    </div>
                    <div class="text-center mt-1">
                        <img src="${novel.cover_url || 'https://mysteriouslamb.oss-cn-hangzhou.aliyuncs.com/icon.jpg'}" 
                             alt="${novel.novel_name}" 
                             class="img-fluid rounded shadow-sm" style="height: 120px; object-fit: cover;">
                    </div>
                    <div class="novel-tags mt-1">
                        <span class="novel-tag small py-0 px-1">热门</span>
                        <span class="novel-tag small py-0 px-1">${novel.update_status === 1 ? '完结' : '连载'}</span>
                    </div>
                </div>
                <a href="#" class="stretched-link" data-novel-id="${novel.novel_id}"></a>
            `);
            
            colContainer.append(card);
            rowContainer.append(colContainer);
        });
        
        carouselItem.append(rowContainer);
        carouselInner.append(carouselItem);
    }
    
    // 添加指示器和内容到轮播图容器
    carouselContainer.append(carouselIndicators);
    carouselContainer.append(carouselInner);
    
    // 添加轮播图控制按钮
    carouselContainer.append(`
        <button class="carousel-control-prev" type="button" data-bs-target="#novelsCarousel" data-bs-slide="prev">
            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
            <span class="visually-hidden">上一页</span>
        </button>
        <button class="carousel-control-next" type="button" data-bs-target="#novelsCarousel" data-bs-slide="next">
            <span class="carousel-control-next-icon" aria-hidden="true"></span>
            <span class="visually-hidden">下一页</span>
        </button>
    `);
    
    // 添加自定义样式
    $('<style>').html(`
        .carousel-control-prev-icon, .carousel-control-next-icon {
            background-color: rgba(0, 0, 0, 0.3);
            border-radius: 50%;
            padding: 10px;
        }
        .carousel-indicators {
            bottom: -10px;
        }
        .carousel-indicators button {
            background-color: #ccc;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin: 0 5px;
        }
        .carousel-indicators button.active {
            background-color: #666;
        }
        /* 添加卡片悬停上浮效果 - 只针对小说卡片 */
        .novel-card {
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        .novel-card:hover {
            transform: translateY(-8px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1) !important;
        }
    `).appendTo('head');
    
    // 添加点击事件
    $('[data-novel-id]').on('click', function(e) {
        e.preventDefault();
        const novelId = $(this).data('novel-id');
        // 跳转到小说详情页 - 修改为跳转到page.jsp
        window.location.href = `/demo1_war_exploded/MainPage/functionPage/page.jsp?id=${novelId}`;
    });
}

/**
 * 渲染小说排行榜样式
 * @param {Array} novels - 小说数据数组
 */
function renderNovelsRanking(novels) {
    // 清空容器
    $('#novels-container').empty();
    
    // 如果没有小说数据
    if (!novels || novels.length === 0) {
        $('#novels-container').html('<div class="col-12 text-center py-5"><h3>暂无小说数据</h3></div>');
        return;
    }
    
    // 创建排行榜容器
    const rowContainer = $('<div>').addClass('row row-cols-1 row-cols-md-3 g-3');
    $('#novels-container').append(rowContainer);
    
    // 遍历小说数据，创建排行榜项
    $.each(novels, function(index, novel) {
        // 排名序号，从1开始
        const rankNum = index + 1;
        
        // 创建列容器
        const colContainer = $('<div>').addClass('col mb-3');
        rowContainer.append(colContainer);
        
        // 排名序号样式
        let rankClass = '';
        if (rankNum === 1) {
            rankClass = 'rank-first';
        } else if (rankNum === 2) {
            rankClass = 'rank-second';
        } else if (rankNum === 3) {
            rankClass = 'rank-third';
        }
        
        // 构建卡片HTML
        const card = $('<div>').addClass('card h-100 shadow-sm border-0');
        colContainer.append(card);
        
        // 卡片内容
        card.html(`
            <div class="card-body p-2">
                <div class="d-flex align-items-start mb-1">
                    <div class="rank-number ${rankClass} me-2" style="font-size: 18px;">${rankNum < 10 ? '0' + rankNum : rankNum}</div>
                    <div class="d-flex flex-column">
                        <h6 class="novel-title mb-0 text-truncate">${novel.novel_name}</h6>
                        <span class="author-name text-muted small">${novel.username || '未知'}</span>
                    </div>
                </div>
                <div class="text-center mt-1">
                    <img src="${novel.cover_url || 'https://mysteriouslamb.oss-cn-hangzhou.aliyuncs.com/icon.jpg'}" 
                         alt="${novel.novel_name}" 
                         class="img-fluid rounded shadow-sm" style="height: 120px; object-fit: cover;">
                </div>
                <div class="novel-tags mt-1">
                    <span class="novel-tag small py-0 px-1">热门</span>
                    <span class="novel-tag small py-0 px-1">${novel.update_status === 1 ? '完结' : '连载'}</span>
                </div>
            </div>
            <a href="#" class="stretched-link" data-novel-id="${novel.novel_id}"></a>
        `);
    });
    
    // 添加点击事件
    $('[data-novel-id]').on('click', function(e) {
        e.preventDefault();
        const novelId = $(this).data('novel-id');
        // 跳转到小说详情页
        window.location.href = `/MainPage/functionPage/novelDetail.jsp?id=${novelId}`;
    });
}

/**
 * 渲染小说列表（原卡片样式，保留作为备用）
 * @param {Array} novels - 小说数据数组
 */
function renderNovels(novels) {
    // 清空容器
    $('#novels-container').empty();
    
    // 如果没有小说数据
    if (!novels || novels.length === 0) {
        $('#novels-container').html('<div class="col-12 text-center py-5"><h3>暂无小说数据</h3></div>');
        return;
    }
    
    // 遍历小说数据，创建卡片
    $.each(novels, function(index, novel) {
        const card = $('<div>').addClass('col');
        card.html(`
            <div class="card novel-card h-100 shadow-sm">
                <img src="${novel.cover_url || 'https://mysteriouslamb.oss-cn-hangzhou.aliyuncs.com/icon.jpg'}" 
                     class="card-img-top" alt="${novel.novel_name}" 
                     style="height: 200px; object-fit: cover;">
                <div class="card-body">
                    <h5 class="card-title">${novel.novel_name}</h5>
                    <p class="card-text text-muted">作者: ${novel.username || '未知'}</p>
                    <p class="card-text small text-truncate">${novel.introduction || '暂无简介'}</p>
                    <span class="badge ${novel.update_status === 1 ? 'bg-success' : 'bg-primary'}">${novel.update_status === 1 ? '完结' : '连载'}</span>
                </div>
                <div class="card-footer bg-transparent border-top-0">
                    <small class="text-muted">发布时间: ${novel.publish_time || '未知'}</small>
                </div>
                <a href="#" class="stretched-link" data-novel-id="${novel.novel_id}"></a>
            </div>
        `);
        $('#novels-container').append(card);
    });
    
    // 添加点击事件
    $('[data-novel-id]').on('click', function(e) {
        e.preventDefault();
        const novelId = $(this).data('novel-id');
        // 跳转到小说详情页
        window.location.href = `/MainPage/functionPage/novelDetail.jsp?id=${novelId}`;
    });
}

/**
 * 渲染分页
 * @param {number} total - 总记录数
 * @param {number} currentPage - 当前页码
 * @param {number} pageSize - 每页数量
 */
function renderPagination(total, currentPage, pageSize) {
    const totalPages = Math.ceil(total / pageSize);
    
    // 如果只有一页，不显示分页
    if (totalPages <= 1) {
        $('#pagination-container').empty();
        return;
    }
    
    // 创建分页HTML
    let paginationHTML = `
        <nav aria-label="小说分页">
            <ul class="pagination">
                <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                    <a class="page-link" href="#" data-page="${currentPage - 1}" aria-label="上一页">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
    `;
    
    // 计算显示的页码范围
    let startPage = Math.max(1, currentPage - 2);
    let endPage = Math.min(totalPages, startPage + 4);
    
    // 如果页码范围不足5页，调整起始页
    if (endPage - startPage < 4) {
        startPage = Math.max(1, endPage - 4);
    }
    
    // 添加页码
    for (let i = startPage; i <= endPage; i++) {
        paginationHTML += `
            <li class="page-item ${i === currentPage ? 'active' : ''}">
                <a class="page-link" href="#" data-page="${i}">${i}</a>
            </li>
        `;
    }
    
    // 添加下一页按钮
    paginationHTML += `
                <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                    <a class="page-link" href="#" data-page="${currentPage + 1}" aria-label="下一页">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
            </ul>
        </nav>
    `;
    
    // 设置分页HTML
    $('#pagination-container').html(paginationHTML);
    
    // 添加分页点击事件
    $('.page-link').on('click', function(e) {
        e.preventDefault();
        if (!$(this).parent().hasClass('disabled')) {
            const page = parseInt($(this).data('page'));
            // 获取当前搜索条件
            const searchInput = $('input[type="search"]');
            const novelName = searchInput.length ? searchInput.val() : '';
            // 重新获取数据
            fetchNovels(page, pageSize, novelName);
        }
    });
}

/**
 * 显示错误信息
 * @param {string} message - 错误信息
 */
function showError(message) {
    // 创建错误提示
    const errorDiv = $('<div>')
        .addClass('alert alert-danger mt-3')
        .attr('role', 'alert')
        .text(message);
    
    // 添加到容器顶部
    $('.container').prepend(errorDiv);
    
    // 5秒后自动消失
    setTimeout(function() {
        errorDiv.fadeOut('slow', function() {
            $(this).remove();
        });
    }, 5000);
}

/**
 * 初始化搜索功能
 */
function initSearch() {
    $('form.d-flex').on('submit', function(e) {
        e.preventDefault();
        const searchInput = $(this).find('input[type="search"]');
        if (searchInput.length) {
            fetchNovels(1, 9, searchInput.val());
        }
    });
}

// 初始化搜索功能
$(document).ready(function() {
    initSearch();
});